package org.bukkit.pm.afk;

import java.util.logging.Level;

import org.bukkit.entity.Player;
import org.bukkit.event.player.PlayerChatEvent;
import org.bukkit.event.player.PlayerEvent;
import org.bukkit.event.player.PlayerListener;
import org.bukkit.event.player.PlayerMoveEvent;

/**
 * Handle events for all Player related events
 * such as commands
 * @author patamau
 */
public class AfkPlayerListener extends PlayerListener {
    private final AfkPlugin _plugin;

    public AfkPlayerListener(AfkPlugin plugin) {
        _plugin = plugin;
    }
    
    public void onPlayerJoin(PlayerEvent event){
    	Player p = event.getPlayer();
    	p.sendMessage("[Afk "+AfkPlugin.VERSION+"] type /afkhelp for available commands");
    }
    
    public void onPlayerMove(PlayerMoveEvent event){
    	Player p = event.getPlayer();
    	if(_plugin.isAfk(p)){
    		//will actually force the player to be removed from away status
    		_plugin.toggleAfk(p,null);
    	}
    }
    
    public void onPlayerQuit(PlayerEvent event){
    	Player p = event.getPlayer();
    	_plugin.removePlayer(p);
    }
    
	@Override
    public void onPlayerCommand(PlayerChatEvent event)  {
    	Player player = event.getPlayer();
        String[] split = event.getMessage().split(" ");
        if(split.length<1) {
        	_plugin.log(Level.WARNING,"command received, but no split available: "+event.getMessage());
        	return; //XXX: is it possible?
        }
        String cmd = split[0];
        event.setCancelled(true); //prevent other plugins or the server to handle this
        if(cmd.equalsIgnoreCase("/afklist")){
        	AfkPlayer[] aps = _plugin.getAfkPlayers();
        	if(aps.length==0){
        		player.sendMessage("[Afk] No players away");
        	}else{
        		player.sendMessage("[Afk] Players:");
	            for(AfkPlayer ap: aps){
	            	player.sendMessage(ap.toString());
	            }
        	}
        }else if(cmd.equalsIgnoreCase("/afkhelp")){
        	//print a list of available commands
        	player.sendMessage("[Afk] command list:");
        	player.sendMessage(" /afklist: shows all the Afk players");
        	player.sendMessage(" /afk [reason]: toggle your AFK status you a single optional reason word");
        }else if(cmd.equalsIgnoreCase("/afk")){
        	String r;
        	if(split.length>1){
        		r = split[1];
        	}else{
        		r = null;
        	}
        	_plugin.toggleAfk(player, r);
        }else{
        	//restore event if it cannot be handled by this plugin
        	event.setCancelled(false);
        }
    }
}
